﻿package net.wangit.util;

import java.security.MessageDigest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Md5Encoder {

	private static final Log log = LogFactory.getLog(Md5Encoder.class);
	private static MessageDigest digest;

	public Md5Encoder() {
	}

	public static synchronized String encode(String str) {
		if (str == null) {
			return "";
		} else {
			digest.update(str.getBytes());
			return toHex(digest.digest());
		}
	}

	private static String toHex(byte[] hash) {
		StringBuffer sb = new StringBuffer(hash.length * 2);
		for (int i = 0; i < hash.length; i++) {
			if ((hash[i] & 0xff) < 16)
				sb.append("0");
			sb.append(Long.toString(hash[i] & 0xff, 16));
		}

		return sb.toString();
	}

	static {
		try {
			digest = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			log.error("Failed to load the MD5 MessageDigest.", e);
			throw new IllegalStateException(
					"Failed to load the MD5 MessageDigest.");
		}
	}
}
